House Robber II

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Solution:

  1. public class Solution {
  2. public int rob(int[] nums) {
  3. if (nums == null || nums.length == 0)
  4. return 0;
  5. int n = nums.length;
  6. if (n == 1)
  7. return nums[0];
  8. if (n == 2)
  9. return Math.max(nums[0], nums[1]);
  10. return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1));
  11. }
  12. int rob(int[] nums, int s, int e) {
  13. int n = e - s + 1;
  14. int[] dp = new int[n + 1];
  15. dp[1] = nums[s];
  16. for (int i = 2; i <= n; i++) {
  17. dp[i] = Math.max(dp[i - 1], nums[s - 1 + i] + dp[i - 2]);
  18. }
  19. return dp[n];
  20. }
  21. }